package com.github.baichuan.application.scaffold.domain.identity;


import com.github.baichuan.application.scaffold.jpa.identity.DingUserRepository;
import com.github.baichuan.web.dto.Result;
import com.github.baichuan.application.scaffold.dto.dingtalk.User;
import com.github.baichuan.web.error.NoSuchEntityException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
@Transactional(rollbackFor = Exception.class)
public class DingUserService {
    @Autowired
    private DingUserRepository identityRepository;
    @Autowired
    private ApplicationMemberService appMemberService;

    public DingUser find(String unionId) {
        return identityRepository.findById(unionId).orElseThrow(() -> new NoSuchEntityException("DingTalkAuth不存在(unionId=" + unionId + ")"));
    }

    public Result bind(String application, String memberUid, User user){
        ApplicationMember appMember = appMemberService.find(application, memberUid);
        Member member = appMember.getMember();
        if(StringUtils.isNotBlank(member.getDingUnionId())){
            return Result.fail("已绑定钉钉账号");
        }

        DingUser dingUser = new DingUser();
        dingUser.setUnionId(user.getUnionId());
        dingUser.setUserId(user.getUserId());
        dingUser.setEmail(user.getEmail());
        dingUser.setMobile(user.getMobile());
        dingUser.setBindTime(LocalDateTime.now());
        identityRepository.save(dingUser);

        member.setDingUnionId(user.getUnionId());
        if(StringUtils.isBlank(member.getMobile())){
            member.setMobile(user.getMobile());
        }
        if(StringUtils.isBlank(member.getEmail())){
            member.setEmail(user.getEmail());
        }
        appMemberService.save(appMember);

        return Result.success("钉钉账号绑定成功");
    }
}
